export function addClass(el, className) {
    if (hasClass(el, className)) {
        return
    }
    let newClass = el.className.split(' ')
    newClass.push(className)
    el.className = newClass.join(' ')
}

export function hasClass(el, className) {
    let reg = new RegExp(`(^|\\s)${className}(\\s|$)`)
    return reg.test(el.className)
}

// 读写dom元素的 data- 属性
export function getData(el, name, val) {
    name = `data-${name}`
    if (val) {
        return el.setAttribute(name, val)
    } else {
        return el.getAttribute(name)
    }
}

// 修改元素颜式
export function getStyle(el, styleName, val, needPrefix) {
    // 该属性是否需要添加浏览器前缀
    if (needPrefix) {
        styleName = prefixStyle(styleName)
    }
    if (val !== undefined) {
        el.style[styleName] = val
    } else {
        return el.style[styleName]
    }
}

// 进行浏览器能力检测
let elementStyle = document.createElement('div').style
let vendor = (() => {
    let transformNames = {
        webkit: 'webkitTransform',
        Moz: 'MozTransform',
        O: 'OTransform',
        ms: 'maTransform',
        standard: 'transform'
    }

    for (let key in transformNames) {
        if (elementStyle[transformNames[key]] !== undefined) {
            return key
        }
    }
    return false
})()
// 添加浏览器前缀
function prefixStyle(style) {
    if (vendor === false) {
        return false
    }

    if (vendor === 'standard') {
        return style
    } else {
        return vendor + style.charAt(0).toUpperCase() + style.substr(1)
    }
}